package org.opensuse.bs.ui;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

public class Parser {
	private File oscrc;
	
	public Parser(File oscrc) {
		this.oscrc = oscrc;
	}
	
	public HashMap<String, HashMap<String, String>> parse() {
		HashMap<String, HashMap<String, String>> sections = 
			new HashMap<String, HashMap<String, String>>();
		try {
			FileReader in = new FileReader(oscrc);
			BufferedReader input = new BufferedReader(in);
			String line;
			String head = "Unkown";
			HashMap<String, String> pairs = new HashMap<String, String>();
			while((line = input.readLine()) != null) {
				String tmp = line.trim();
				if(tmp.length() == 0 || tmp.charAt(0) == '#') { // empty line or comment line
					continue;
				}
				if(tmp.startsWith("[") && tmp.endsWith("]")) {
					if(!pairs.isEmpty()) {
						sections.put(head, pairs);
					}
					head = tmp.substring(1, tmp.length()-1).trim();
					pairs = new HashMap<String, String>();
					continue;
				}
				String regex = null;
				int colon = line.indexOf(":");
				int equals = line.indexOf("=");
				if(colon != -1 && (equals == -1 || colon < equals)) {
					regex = ":";
				}
				else if(equals != -1) {
					regex = "=";
				}
				else {
					System.err.println("Unknown line in .oscrc: " + line);
					continue;
				}
				String[] pair = line.split(regex);
				if(pair.length == 2) {
					pairs.put(pair[0].trim(), pair[1].trim());
				}
			}
			sections.put(head, pairs);
			input.close();
		}catch(IOException e) {
			System.err.println(e.getMessage());
		}
		if(sections.isEmpty())
			return null;
		else
			return sections;
	}

}
